<?php

namespace app\index\service;

use \app\index\model\Member;
use \app\index\model\Plan as PlanModel;

class Plan
{

    /**
     * 获取挑战列表
     * @param type $state
     * @param type $user_id
     * @return type
     */
    public static function getPlanList($state, $user_id)
    {
        $where = [
            "member_id" => $user_id,
            'state' => $state,
        ];
        if ($state)
        {
            $plan_model_list = PlanModel::where($where)->order('finish_time desc')->select();
            foreach ($plan_model_list as $key => $value)
            {
                $plan_model_list[$key]['finish_time'] = to_date($value['finish_time'], 'n月j日');
            }
            $plan_list = array_group_plus($plan_model_list, 'finish_time');
        }
        else
        {
            $plan_model_list = PlanModel::where($where)
                    ->whereTime('plan_time', "<=", strtotime(to_date(time(), "Y-m-d 23:59:59")))
                    ->order('plan_time')
                    ->select();
            foreach ($plan_model_list as $key => $value)
            {
                $plan_model_list[$key]['plan_time'] = to_date($value['plan_time'], 'n月j日');
            }
            $plan_list = array_group_plus($plan_model_list, 'plan_time');
        }
        return $plan_list;
    }

    /**
     * 更改挑战的状态,如果有周期则写入新的挑战
     * @param type $user_id
     * @param type $id
     * @return type
     */
    public static function change_state($user_id,$id)
    {
        $plan_model = PlanModel::get($id);
        if (!empty($plan_model)&&$user_id == $plan_model->member_id)
        {
            $data = [
                'state' => 1 - $plan_model->state,
                'finish_time' => time(),
            ];
            $plan_model->save($data);
            static::writeCycle($plan_model);
            return json([ 'code' => 1, 'msg' => '操作成功', 'data' => $plan_model->toArray() ]);
        }
        else
        {
            return json([ 'code' => 0, 'msg' => '非法提交' ]);
        }
    }

    /**
     * 根据挑战状态和周期判断是否需要写入新的挑战
     * @param type $plan_model
     */
    public static function writeCycle($plan_model)
    {
        if ($plan_model['state'] == 1 && !empty($plan_model['cycle']))
        {
            $p_timestamp = to_timestamp($plan_model['plan_time']);
            $finish_time = to_timestamp($plan_model['finish_time']);
            $endline = to_timestamp(to_date(time(), "Y-m-d 23:59:59"));
//              生成任务日期必须是今天往后
            while ($p_timestamp <= $endline)
            {
                $p_timestamp = strtotime("+ " . $plan_model['cycle'] . " day", $p_timestamp);
            }
            $data = [
                'state' => 1 - $plan_model['state'],
                'plan_time' => $p_timestamp,
                'plan_str' => $plan_model['plan_str'],
                'cycle' => $plan_model['cycle'],
                'member_id' => $plan_model['member_id'],
            ];
            $one = PlanModel::where($data)->find();
            if (empty($one))
            {
                //不存在相同的才插入
                PlanModel::create($data);
            }
        }
    }

    /**
     * 计算一段时间内,统计每一天的情况
     * @param type $where
     * @param type $start_date
     * @param type $end_date
     * @return type
     */
    public static function count_daily($where, $start_date, $end_date)
    {
        $start_timestamp = to_timestamp($start_date);
        $end_timestamp = to_timestamp($end_date);
//        $where_time = [
//            [ 'finish_time', 'between time', [ $start_date, $end_date ] ],
//        ];
        $field = [
            'count(id)' => 'count',
            'from_unixtime(finish_time, "%c月%e日" )' => 'date',
        ];
        $res = PlanModel::whereTime('finish_time', 'between', [ $start_date, $end_date ])
                ->where($where)
                ->group('from_unixtime(finish_time, "%c-%e" )')
                ->field($field)
                ->select()
                ->toArray();
        $res = array_column($res, 'count', 'date');
        $temp_timestamp = $start_timestamp;
        $dailyCount = [];
        while ($temp_timestamp <= $end_timestamp)
        {
            $temp_date = to_date($temp_timestamp, "n月j日");
            $month_day = to_date($temp_timestamp, "j日");
            $dailyCount[$month_day] = 0;
            if (!empty($res[$temp_date]))
            {
                $temp = $res[$temp_date];
                $dailyCount[$month_day] = round($temp);
            }
            $temp_timestamp += 86400;
        }
        return $dailyCount;
    }

    /**
     * 某年内,统计每个月的情况
     * @param array $where
     * @param type $year
     * @param type $count
     * @return type
     */
    public static function count_year($where = [], $year = null, $count = 'count(id)')
    {
        $time_column = "finish_time";
        $time_format = "from_unixtime";
        if (empty($year))
        {
            $year = date('Y');
        }
        $time_arr = [
            date($year . "-1-1 00:00:00"),
            date($year . "-12-31 23:59:59"),
        ];
        $result = PlanModel::where($where)
                ->whereTime('finish_time', 'between', $time_arr)
                ->group('temp_month')
                ->field("$time_format($time_column,'%c') as temp_month,$count as value")
                ->select();
        $result = array_column($result->toArray(), 'value', 'temp_month');
        $year_value = [];
        for ($i = 1; $i <= 12; $i++)
        {
            $index = $i;
            if (!empty($result[$index]))
            {
                $temp = $result[$index];
                $year_value[$i . "月"] = money_float($temp);
            }
            else
            {
                $year_value[$i . "月"] = 0;
            }
        }
        return $year_value ?: [];
    }

}
